<template>
  <div class="full">
    <div class="WebTitle">
      <span class="title">GUGUCode</span>
    </div>

    <transition name="fade">
      <div class="form" v-if="view === 'login'">
        <div class="login-title">
          <span>登录</span>
        </div>
        <div class="account">
          <div><Input01 placeholder="请输入账号" style="width: 350px;" v-model="loginForm.account" /></div>
        </div>
        <div class="password">
          <div><Input01 placeholder="请输入密码" style="width: 350px;" v-model="loginForm.password" type="password" /></div>
        </div>
        <div class="remember-password">
          <label class="checkbox-label">
            <input 
              type="checkbox" 
              v-model="loginForm.remember"
              class="custom-checkbox"
            >
            <span>记住密码</span>
          </label>
        </div>
        <div class="moveToRegister">
          <div style="width: 350px;">
            <span class="register-span" @click="gotoRegister">点击注册</span>
          </div>
        </div>
        <div class="login-button">
          <Button01 content="登录" @click="handleLogin"></Button01>
        </div>
        <div class="login-divider">
          <span>其他方式登录</span>
        </div>

        <div class="login-picture">
          <div>
            <img src="../assets/QQ.png" alt="QQ登录">
          </div>
          <div>
            <img src="../assets/WeChat.png" alt="微信登录"></img>
          </div>
        </div>
      </div>
    </transition>

    <transition name="fade">
      <div class="form" v-if="view === 'register'">
        <div class="register-title">
          <span>注册</span>
        </div>
        <div class="email">
          <div><Input01 placeholder="请输入邮箱" style="width: 350px;" v-model="RegisterUser.email"/></div>
        </div>
        <div class="verify">
          <div style="display: flex; justify-content: space-between; width: 350px;">
            <Input01 
              placeholder="请输入验证码" 
              style="width: 200px;" 
              v-model="RegisterUser.code"
              type="text"
              maxlength="6" 
            />
            <div @click="getVerifyCode">
              <Button02 
                :content="registerButtonContent" 
                class="verify-send-button" 
                :disabled="!isEmailValid || registerButtonContent !== '获取验证码'"
              ></Button02>
            </div>
          </div>
        </div>
        <div class="account">
          <div><Input01 placeholder="请输入账号" style="width: 350px;" v-model="RegisterUser.account" /></div>
        </div>
        <div class="password">
          <div><Input01 placeholder="请输入密码" style="width: 350px;" v-model="RegisterUser.password" /></div>
        </div>
        <div class="password-repeat">
          <div><Input01 placeholder="请确认你的密码" style="width: 350px;" v-model="RegisterUser.confirmPassword" /></div>
        </div>
        <div class="register-button">
          <Button01 content="注册" @click="register"></Button01>
        </div>

        <div class="moveToRegister">
          <div style="width: 350px;">
            <span class="register-span" @click="backtologin">返回登录</span>
          </div>
        </div>
      </div>
    </transition>

    <transition name="fade">
      <div class="form" v-if="view === 'userInfo'">
        <div class="register-title">
          <span>完善个人信息</span>
        </div>
        
        <!-- 用户昵称 -->
        <div class="info-item">
          <div><Input01 placeholder="请输入昵称" style="width: 350px;" v-model="UserInfo.nickname"/></div>
        </div>

        <!-- 出生日期 -->
        <div class="info-item">
          <div class="date-picker-wrapper">
            <input 
              type="date" 
              class="custom-date-input"
              v-model="UserInfo.birthday"
            />
          </div>
        </div>

        <!-- 性别选择 -->
        <div class="info-item">
          <div class="gender-select">
            <div 
              class="gender-option" 
              :class="{ active: UserInfo.gender === '男' }"
              @click="UserInfo.gender = '男'"
            >
              男
            </div>
            <div 
              class="gender-option" 
              :class="{ active: UserInfo.gender === '女' }"
              @click="UserInfo.gender = '女'"
            >
              女
            </div>
          </div>
        </div>

        <!-- 用户简介 -->
        <div class="info-item">
          <textarea 
            class="custom-textarea"
            placeholder="请输入个人简介"
            v-model="UserInfo.description"
            maxlength="200"
          ></textarea>
          <div class="word-count">{{ UserInfo.description.length }}/200</div>
        </div>

        <!-- 用户头像 -->
        <div class="info-item">
          <div class="avatar-upload">
            <input 
              type="file" 
              accept="image/*" 
              @change="handleAvatarUpload" 
              ref="avatarInput"
              style="display: none"
            />
            <div class="avatar-preview" @click="$refs.avatarInput.click()">
              <img v-if="UserInfo.avatarUrl" :src="UserInfo.avatarUrl" alt="头像预览"/>
              <div v-else class="avatar-placeholder">
                <i class="fas fa-plus"></i>
                <span>上传头像</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-button">
          <Button01 content="保存" @click="submitUserInfo"></Button01>
        </div>
      </div>
    </transition>

    <Vcode :show="isShow" @success="success" @close="close"></Vcode>
    <MessagePopup
      :visible.sync="messageVisible"
      :type="messageType"
      :message="messageText"
      :duration="2000"
    />
  </div>
</template>

<script>
import Input01 from '@/components/Input01.vue';
import Button01 from '@/components/Button01.vue';
import Button02 from '@/components/Button02.vue';
import { baseURL } from '@/utils/api';
import axios from 'axios';
import Vcode from "vue-puzzle-vcode";
import md5 from 'js-md5';
import MessagePopup from '@/components/MessagePopup.vue';

export default {
  name: 'LoginView',
  components: {
    Input01,
    Button01,
    Button02,
    Vcode,
    MessagePopup
  },
  data() {
    return {
      view: "login",
      isShow: false,
      registerButtonContent: "获取验证码",
      isEmailValid: false,
      isCodeValid: false,
      
      // 重构为 RegisterUser 对象
      RegisterUser: {
        email: "",
        code: "",     // 验证码
        account: "",
        password: "",
        confirmPassword: ""  // 用于前端验证，不会发送给后端
      },

      messageVisible: false,
      messageType: 'success',
      messageText: '',
      UserInfo: {
        nickname: '',
        birthday: '',
        gender: '',
        description: '',
        avatarUrl: '',
        avatarFile: null
      },
      loginForm: {
        account: '',
        password: '',
        remember: false
      }
    };
  },
  watch: {
    // 更新邮箱验证监听器
    'RegisterUser.email'(value) {
      const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      this.isEmailValid = emailPattern.test(value);
      console.log('Email:', value, 'Is Valid:', this.isEmailValid);
    },
    // 更新验证码验证监听器
    'RegisterUser.code'(value) {
      const codePattern = /^[A-Za-z0-9]{6}$/;
      this.isCodeValid = codePattern.test(value);
      console.log('Code:', value, 'Is Valid:', this.isCodeValid);
    }
  },
  computed: {
  },
  created() {
    // 页面加载时获取存储的登录信息
    this.getStoredLoginInfo();
  },
  methods: {
    //滑块验证码验证成功
    success(msg) {
      this.isShow = false; // 通过验证后，需要手动隐藏模态框
      console.log(baseURL+"/email-service/mail/getRegisterCode");
      //发送验证码请求
      axios({
        method:'get',
        url: baseURL+"/email-service/mail/getRegisterCode",
        params: {
          mail:this.RegisterUser.email
        }
      }).then(res=>{
        console.log(res.data);
        //验证码请求后端成功
        if (res.data.result=="success") {
          this.showMessage('success', '验证码发送成功，请查收邮件');
          
          let countdownTime = 60;
          const countdownInterval = setInterval(() => {
            if (countdownTime > 0) {
              countdownTime--;
              this.registerButtonContent = `${countdownTime}s后Retry`;
            } else {
              clearInterval(countdownInterval);
              this.registerButtonContent = '获取验证码';
            }
          }, 1000);
        }
      })
    },
      // 用户点击遮罩层，应该关闭模态框
      close() {
        this.isShow = false;
      },
    //跳转注册页面
    gotoRegister() {
      this.view = "register";
    },
    //返回登录页面  
    backtologin(){
      this.view = "login";
    },
    //滑块验证码显示
    getVerifyCode(){
      if (this.registerButtonContent === '获取验证码' && this.isEmailValid) {
        this.isShow = true;
      }
    },
    //显示消息
    showMessage(type, text) {
      this.messageType = type;
      this.messageText = text;
      this.messageVisible = true;
    },
    //注册
    register() {
      if (this.RegisterUser.code.length != 6) {
        this.showMessage('error', '验证码格式错误');
        return;
      }
      if (this.RegisterUser.password != this.RegisterUser.confirmPassword) {
        this.showMessage('error', '密码不一致');
        return;
      }
      if (!this.RegisterUser.account || !this.RegisterUser.password || !this.RegisterUser.email) {
        this.showMessage('error', '请填写完整信息');
        return;
      }


      axios({
        method: 'get',
        url: baseURL + '/email-service/mail/verifyRegisterCode',
        params: {
          mail: this.RegisterUser.email,
          code: this.RegisterUser.code
        }

      }).then(res => {
        if (res.data.result === "success") {
          // 验证码验证成功，继续注册流程
          console.log('验证码验证成功');
          this.proceedWithRegistration();

        } else {
          console.log(res.data);
          this.showMessage('error', res.data.message);
        }
      }).catch(error => {
        this.showMessage('error', '验证码验证失败');
        console.error('验证码验证错误:', error);
      });
    },

    proceedWithRegistration() {
      const userForSubmit = {
        user_id: "",
        user_email: this.RegisterUser.email,
        user_account: this.RegisterUser.account,
        user_password: md5(this.RegisterUser.password),
        user_createtime: "" 
      };
      
      axios({
        method: 'post',
        url: baseURL + '/user-service/user/register',
        data: userForSubmit,
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.data.result === "success") {
          // 将 user_id 存入 localStorage
          localStorage.setItem('userId', res.data.user_id);
          this.showMessage('success', '注册成功，请完善个人信息');
          this.view = 'userInfo';
        } else {
          this.showMessage('error', res.data.message || '注册失败');
        }
      }).catch(error => {
        this.showMessage('error', '注册失败，请稍后重试');
        console.error('注册错误:', error);
      });
    },

    // 处理头像上传
    handleAvatarUpload(event) {
      const file = event.target.files[0];
      if (file) {
        this.UserInfo.avatarFile = file;
        this.UserInfo.avatarUrl = URL.createObjectURL(file);
      }
    },

    // 提交用户信息
    submitUserInfo() {
      const formData = new FormData();
      
      // 从 localStorage 获取 userId
      formData.append('user_id', localStorage.getItem('userId'));
      formData.append('user_name', this.UserInfo.nickname);
      formData.append('user_birth', this.UserInfo.birthday);
      formData.append('user_sex', this.UserInfo.gender);
      formData.append('user_introduction', this.UserInfo.description);
      
      if (this.UserInfo.avatarFile) {
        formData.append('file', this.UserInfo.avatarFile);
      }

      axios({
        method: 'post',
        url: baseURL + '/user-service/user/registerUserInfos',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.data.result === "success") {
          this.showMessage('success', '信息保存成功');
          this.backtologin();
        } else {
          this.showMessage('error', res.data.message || '保存失败');
        }
      }).catch(error => {
        this.showMessage('error', '保存失败，请稍后重试');
        console.error('保存用户信息错误:', error);
      });
    },

    //登录
    handleLogin() {
      if (!this.loginForm.account || !this.loginForm.password) {
        this.showMessage('error', '请输入账号和密码');
        return;
      }

      axios({
        method: 'get',
        url: baseURL + '/user-service/user/login',
        params: {
          account: this.loginForm.account,
          password: md5(this.loginForm.password)
        }
      }).then(res => {
        if (res.data.result === "success") {
          this.saveLoginInfo();
          
          // 存储 userId 和 token 到 localStorage
          localStorage.setItem('userId', res.data.user_id);
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('userAccount', this.loginForm.account);
          
          this.showMessage('success', '登录成功');
          
          setTimeout(() => {
            this.$router.push('/home');
          }, 1500);
        } else {
          this.showMessage('error', res.data.message || '登录失败');
        }
      }).catch(error => {
        console.error('登录错误:', error);
        this.showMessage('error', '登录失败，请稍后重试');
      });
    },

    // 获取存储的登录信息
    getStoredLoginInfo() {
      // 获取账号
      const storedAccount = localStorage.getItem('userAccount');
      if (storedAccount) {
        this.loginForm.account = storedAccount;
      }

      // 获取"记住密码"状态
      const rememberPassword = localStorage.getItem('rememberPassword');
      if (rememberPassword === 'true') {
        this.loginForm.remember = true;
        // 如果记住密码，则获取存储的密码
        const storedPassword = localStorage.getItem('userPassword');
        if (storedPassword) {
          this.loginForm.password = storedPassword;
        }
      }
    },

    // 保存登录信息
    saveLoginInfo() {
      // 始终保存账号
      localStorage.setItem('userAccount', this.loginForm.account);
      
      // 保存"记住密码"状态
      localStorage.setItem('rememberPassword', this.loginForm.remember);
      
      // 如果选择记住密码，则保存密码
      if (this.loginForm.remember) {
        localStorage.setItem('userPassword', this.loginForm.password);
      } else {
        // 如果取消记住密码，则删除存储的密码
        localStorage.removeItem('userPassword');
      }
    }
  }
};
</script>

<style scoped>
.full {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.WebTitle {
  width: 100%;
  height: 15vh;
  min-height: 80px;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.title {
  margin-left: 15px;
  height: 40px;
  font-size: 32px;
  font-weight: 600;
  color: #2c3e50;
  font-family: 'Poppins', sans-serif;
  letter-spacing: 1px;
}

.form {
  width: 450px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
  backdrop-filter: blur(4px);
  margin-top: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  margin-bottom: 20px;
}

.form:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(31, 38, 135, 0.2);
}

.login-title, .register-title {
  font-size: 32px;
  color: #2c3e50;
  font-weight: 600;
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.email, .verify, .account, .password, .password-repeat {
  width: 100%;
  height: 65px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
}

.verify-send-button {
  width: 110px;
  height: 45px;
  margin-left: 10px;
  transition: all 0.3s ease;
}

.register-button, .login-button {
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.register-span {
  color: #3498db;
  transition: all 0.3s ease;
  font-weight: 500;
}

.register-span:hover {
  color: #2980b9;
  text-decoration: underline;
}

/* 优化过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: center;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
  transform: scale(0.95);
}

.login-divider {
  display: flex;
  align-items: center;
  text-align: center;
  color: #7f8c8d;
  font-size: 14px;
  margin: 30px auto;
  width: 80%;
}

.login-divider::before,
.login-divider::after {
  content: "";
  flex: 1;
  height: 1px;
  background: #e0e0e0;
  margin: 0 15px;
}

.login-picture {
  width: 100%;
  height: 60px;
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.login-picture > div {
  width: 45px;
  height: 45px;
  transition: all 0.3s ease;
}

.login-picture > div > img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: white;
  cursor: pointer;
  padding: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.login-picture > div > img:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

/* 添加响应式设计 */
@media (max-width: 500px) {
  .form {
    width: 90%;
    padding: 20px;
  }
}

.info-item {
  width: 100%;
  margin-bottom: 20px;
}

.custom-date-input {
  width: 350px;
  height: 45px;
  padding: 0 16px;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  font-size: 15px;
  color: #333;
  background-color: rgba(255, 255, 255, 0.9);
}

.gender-select {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.gender-option {
  width: 165px;
  height: 45px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.9);
}

.gender-option.active {
  background-color: #7bb9f8;
  color: white;
  border-color: #7bb9f8;
}

.custom-textarea {
  width: 350px;
  height: 120px;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  font-size: 15px;
  resize: none;
  background-color: rgba(255, 255, 255, 0.9);
}

.word-count {
  text-align: right;
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.avatar-upload {
  display: flex;
  justify-content: center;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 60px;
  border: 2px dashed #e8e8e8;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
}

.avatar-preview:hover {
  border-color: #7bb9f8;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #999;
}

.avatar-placeholder i {
  font-size: 24px;
}

.submit-button {
  margin-top: 30px;
}

.remember-password {
  width: 350px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
  color: #666;
  font-size: 14px;
}

.custom-checkbox {
  margin-right: 8px;
  width: 16px;
  height: 16px;
  cursor: pointer;
}
</style>